package com.example.common;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域配置
 */
@Configuration
public class CorsConfig {

    @Bean
    public CorsFilter corsFilter() {
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();

        CorsConfiguration corsConfiguration = new CorsConfiguration();
        // 配置允许的域名
        corsConfiguration.addAllowedOrigin("http://localhost:5173");
        corsConfiguration.addAllowedOrigin("https://www.chessunyan.asia:5173");
        corsConfiguration.addAllowedOrigin("https://www.chessunyan.asia");
        // 是否允许携带认证信息（cookies等）
        corsConfiguration.setAllowCredentials(true);
        // 允许的头部信息
        corsConfiguration.addAllowedHeader("*");
        // 允许的HTTP方法（GET, POST, PUT等）
        corsConfiguration.addAllowedMethod("*");

        // 应用到所有路径，包括 WebSocket
        source.registerCorsConfiguration("/**", corsConfiguration);

        return new CorsFilter(source);
    }
}
